# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/1/30
# python-version    : Python 3.7.0
# description       : 字典操作工具

import json
from com.articles.microapp.utils.logger_utils import Logger

logger = Logger()


class Dict(dict):
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__


def dict2obj(dictObj):
    try:
        if not isinstance(dictObj, dict):
            return dictObj
        inst = Dict()
        for k, v in dictObj.items():
            inst[k] = dict2obj(v)
        return inst
    except Exception as e:
        logger.error('将字典转换成对象失败，%s', e)
        return None


def str2dict(json_str):
    try:
        json_str = str.replace(json_str, '\'', '"')
        json_str = str.replace(json_str, '\\\\', '')
        json_str = str.replace(json_str, '\\n', '')
        return json.loads(json_str, encoding='utf-8')
    except Exception as e:
        logger.error('将字符串转换成字典对象失败，%', e)
        return None


if __name__ == '__main__':
    # dicts = {'typeId': 3, 'typeName': '小说', 'status': '0', 'createTime': '2019-01-30 10:55:36'}
    #
    # inst = dict2obj(dicts)
    # print(inst.typeId)
    string = '{"typeId": 1,"typeName": "新闻","STATUS": "0","createTime": "2019-01-29 14:07:14"}'
    dict = str2dict(string)
    print(dict)
    print(type(dict))
